﻿import cgi
from google.appengine.ext import db
from google.appengine.ext import webapp
from google.appengine.api import users
from entities import Entities
from Entities import *
def Get(keyNguoiDung, CapBacID=0):
    try:
        nguoidung = NguoiDung.get(db.Key(keyNguoiDung)) 
    except:
        return "Invalid Key"
    capbac_list = []
    if CapBacID > 0:
        capbacs = capbac.get_by_id(CapBacID)
        capbac_dict ={}
        capbac_dict['CapBacID'] = capbacs.key().id()
        capbac_dict['TenCapBac'] = capbacs.TenCapBac   
        capbac_list.append(capbac_dict)
    else:
        capbacs = CapBac.all()
        for capbac in capbacs:
            capbac_dict ={}
            capbac_dict['CapBacID'] = capbac.key().id()
            capbac_dict['TenCapBac'] = capbac.TenCapBac   
            capbac_list.append(capbac_dict)
    tuple_capbac = tuple(capbac_list)  
    return tuple_capbac

def Add(TenCapBac):
    capbac = db.GqlQuery("SELECT * FROM CapBac WHERE TenCapBac = :1",
                              TenCapBac)
    if capbac.count() == 0:                      
        capbac = CapBac(TenCapBac=TenCapBac)
        capbac.put()         
        return "Complete"
    else:
        return "Duplicate"

def Update(CapBacID, TenCapBac):
    capbac_update = capbac.get_by_id(CapBacID)
    capbac = db.GqlQuery("SELECT * FROM CapBac WHERE TenCapBac = :1 AND NguoiDung = :2",
                              TenCapBac, nguoidung)
    if capbac.count() == 0:
        capbac_update.TenCapBac = TenCapBac
        capbac_update.put()
        return "Complete"
    else:
        return "Duplicate"
